//======================================================================
//    This file is part of baijie_interface
//
//    Copyright (C) 2023 Shenzhen Baijie Technology Co., Ltd.All rights reserved.
//
//    filename : bluetooth_interface.cpp
//
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//======================================================================

#include "bluetooth_interface.h"

static int g_bluetoothScanFlag;

bluetooth_interface::bluetooth_interface(QObject *parent) : QObject(parent)
{
}

bluetooth_interface::~bluetooth_interface()
{

}

QString bluetooth_interface::executeLinuxCmd(QString strCmd)
{
    QProcess pro;
    pro.start("bash", QStringList() <<"-c" << strCmd);
    pro.waitForFinished(-1);
    QString strResult = pro.readAllStandardOutput();
    pro.close();
    return strResult;
}

void bluetooth_interface::bluetoothInint()
{
    QString strCmd;
    QString strResult;
    QString str;

    if(g_bluetoothScanFlag == 0)       //  Function: Initializing Bluetooth
    {
        QString out = executeLinuxCmd("cat /usr/bin/bluetooth_set.sh");
        QStringList list = out.split("\n");
        QStringList btScanList;

        list.removeAll("");
        for(int i = 0;i<list.size();i++)
        {
            str = QString(list[i]);
            if(str.contains("bluetoothctl",Qt::CaseSensitive))
            {
                continue;
            }
            btScanList << str + "\n";
        }

        QFile file("/usr/helperboard/qt/bin/bluetooth_enble.sh");
        if (file.exists())
        {
            file.remove();
        }
        if (file.open(QIODevice::WriteOnly | QIODevice::Text))
        {
            for (const QString &line : btScanList)
            {
                QByteArray data = line.toUtf8(); // 使用 toUtf8
                file.write(data); // 写入 QByteArray
            }
        }
        file.close();
        strResult = executeLinuxCmd("chmod +x /usr/helperboard/qt/bin/bluetooth_enble.sh");

        strCmd = QString(". /usr/helperboard/qt/bin/get_bluetooth_ps.sh");
        strResult = executeLinuxCmd(strCmd);
        strResult.remove(strResult.size()-1,1);
        strCmd = QString("ps -ax |grep '%1' |grep -v grep |wc -l").arg(strResult);
        strResult = executeLinuxCmd(strCmd);
        if(strResult == "0\n")
        {
            strCmd = QString("/usr/helperboard/qt/bin/bluetooth_enble.sh");
            strResult = executeLinuxCmdBluetoothOpen(strCmd);
        }

        g_bluetoothScanFlag++;
        strCmd = QString("rm /usr/helperboard/qt/bin/bluetooth_enble.sh");
        strResult = executeLinuxCmd(strCmd);
    }
}

QString bluetooth_interface::bluetoothConnectFlag()
{
    QStringList list;
    list << "#!/usr/bin/expect -f \n"
         << "spawn bluetoothctl              \n"
         << "send \"info \\r\"       \n"
         << "send \"quit\\r\"                \n"
         << "expect \"eof\"                  \n";

    QFile file("/usr/helperboard/qt/bin/bluetooth_connect_flag.sh");
    if (file.exists())
    {
        file.remove();
    }

    if (file.open(QIODevice::WriteOnly | QIODevice::Text))
    {
        for (const QString &line : list)
        {
            QByteArray data = line.toUtf8(); // 使用 toUtf8
            file.write(data); // 写入 QByteArray
        }
    }
    file.close();
    QString strCmd = QString("chmod +x /usr/helperboard/qt/bin/bluetooth_connect_flag.sh");
    executeLinuxCmd(strCmd);

    strCmd = QString("/usr/helperboard/qt/bin/bluetooth_connect_flag.sh");
    QString strResult = executeLinuxCmd(strCmd);
    QString str = QString("Missing device address argument");
    if(strResult.contains(str,Qt::CaseInsensitive))
    {
        return "1";
    }
    else
    {
        QString strFlag = "Agent registered";
        if(strResult.contains(strFlag,Qt::CaseInsensitive))
        {
            int strFlagLocate = strResult.indexOf(strFlag);
            strResult = strResult.remove(0,strFlagLocate);
            QStringList connectList = strResult.split("\n");
            str = connectList.at(3);
            str = str.section(":",1,1);
            str.remove("\r");
            str.remove(0,1);
            return str;
        }
        return "1";
    }
}

void bluetooth_interface::bluetoothDisconnect(QString btAddress)
{
    QStringList list;
    list << "#!/usr/bin/expect -f \n"
         << "set address [lindex $argv 0]    \n"
         << "set prompt \"#\"                \n"
         << "log_user 1                      \n"
         << "spawn bluetoothctl              \n"
         << "send \"disconnect $address\\r\" \n"
         << "send \"quit\\r\"                \n"
         << "expect \"eof\"                  \n";

    QFile file("/usr/helperboard/qt/bin/bluetooth_disconnect.sh");
    if (file.exists())
    {
        file.remove();
    }

    if (file.open(QIODevice::WriteOnly | QIODevice::Text))
    {
        for (const QString &line : list)
        {
            QByteArray data = line.toUtf8(); // 使用 toUtf8
            file.write(data); // 写入 QByteArray
        }
    }
    file.close();
    QString strCmd = QString("chmod +x /usr/helperboard/qt/bin/bluetooth_disconnect.sh");
    executeLinuxCmd(strCmd);

    strCmd = QString("/usr/helperboard/qt/bin/bluetooth_disconnect.sh %1").arg(btAddress);
    executeLinuxCmd(strCmd);
    strCmd = QString("rm /usr/helperboard/qt/bin/bluetooth_disconnect.sh");
    executeLinuxCmd(strCmd);
}

QString bluetooth_interface::executeLinuxCmdBluetoothOpen(QString strCmd)
{
    QProcess pro;
    pro.start("bash", QStringList() <<"-c" << strCmd);
    QThread::sleep(1);
    pro.waitForFinished(-1);
    QString strResult = pro.readAllStandardOutput();
    pro.close();
    return strResult;
}
